package com.boot.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.micrometer.common.util.StringUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Data
@Component
@ConfigurationProperties(prefix = "jwt.token")
public class JwtHelper {
    private int tokenExpiration;
    private static SecretKey tokenSignKeys;

    static {
        try {
            tokenSignKeys = JwtKey.getSecretKey();
        } catch (Exception e) {
            throw new RuntimeException("Failed to load JWT key", e);
        }
    }

    public String createToken(Long userId) {
        System.out.println(userId);
        Claims claims = Jwts.claims()
                .setExpiration(new Date(System.currentTimeMillis() + (long) tokenExpiration * 1000 * 60));
        claims.put("userId", String.valueOf(userId));
        return Jwts.builder()
                .setClaims(claims)
                .signWith(tokenSignKeys)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) return null;
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(tokenSignKeys)
                .build()
                .parseClaimsJws(token)
                .getBody();
        String userIdStr = claims.get("userId", String.class);
        Integer userId = Integer.parseInt(userIdStr);
        return userId.longValue();
    }

    public Boolean isExpiration(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(tokenSignKeys)
                    .build()
                    .parseClaimsJws(token)
                    .getBody().getExpiration().before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    public String createRefreshToken(Long userId) {
        Claims claims = Jwts.claims()
                .setExpiration(new Date(System.currentTimeMillis() + 30L * 24 * 60 * 1000 * 60));
        claims.put("userId", String.valueOf(userId));
        return Jwts.builder()
                .setClaims(claims)
                .signWith(tokenSignKeys)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public Result getRefreshToken(String token) {
        if (StringUtils.isEmpty(token) || isExpiration(token))
            return Result.build("refreshToken 已过期", ResultCodeEum.NOTLOGIN);
        Long userId = getUserId(token);
        String newToken = createToken(userId);
        return Result.build(Map.of("token", newToken), ResultCodeEum.SUCCESS);
    }
}
